<template>
  <n-space class="header-left-btn" :wrap="false" :size="25">
    <n-button size="small" quaternary @click="goHomeHandle()">
      <template #icon>
        <n-icon :depth="3">
          <home-icon></home-icon>
        </n-icon>
      </template>
    </n-button>
    <n-space :wrap="false">
      <!-- 头部按钮 tabbar 元素 -->
      <n-tooltip v-for="item in btnList" :key="item.key" placement="bottom" trigger="hover">
        <template #trigger>
          <n-button size="small" ghost :type="styleHandle(item)" :focusable="false" @click="clickHandle(item)">
            <component :is="item.icon"></component>
          </n-button>
        </template>
        <span>{{ item.title }}</span>
      </n-tooltip>

      <n-divider vertical/>

      <!-- 前进后退按钮 -->
      <n-tooltip v-for="item in historyList" :key="item.key" placement="bottom" trigger="hover">
        <template #trigger>
          <n-button size="small" ghost type="primary" :disabled="!item.select" @click="clickHistoryHandle(item)">
            <component :is="item.icon"></component>
          </n-button>
        </template>
        <span>{{ item.title }}</span>
      </n-tooltip>

      <n-divider vertical/>

      <!-- 保存按钮 -->
      <n-tooltip v-for="item in saveList" :key="item.key" placement="bottom" trigger="hover">
        <template #trigger>
          <n-button size="small" ghost type="primary" :disabled="!item.select" @click="clickSaveHandle(item)">
            <component :is="item.icon"></component>
          </n-button>
        </template>
        <span>{{ item.title }}</span>
      </n-tooltip>
    </n-space>
  </n-space>
</template>

<script setup lang="ts">
import {toRefs, Ref, reactive, computed} from 'vue'
import {
  renderIcon,
  goDialog,
  goHome,
  fetchPathByName,
  getLocalStorage,
  setSessionStorage,
  routerTurnByPath, JSONStringify, MessageSuccess, MessageError
} from '@/utils'
import {icon} from '@/plugins'
import {useRemoveKeyboard} from '../../hooks/useKeyboard.hook'
import {useRoute} from 'vue-router'
import {useChartEditStore} from '@/store/modules/chartEditStore/chartEditStore'

import {useChartHistoryStore} from '@/store/modules/chartHistoryStore/chartHistoryStore'
import {HistoryStackEnum} from '@/store/modules/chartHistoryStore/chartHistoryStore.d'

import {useChartLayoutStore} from '@/store/modules/chartLayoutStore/chartLayoutStore'
import {ChartLayoutStoreEnum} from '@/store/modules/chartLayoutStore/chartLayoutStore.d'
import {PreviewEnum} from "@/enums/pageEnum";
import {StorageEnum} from "@/enums/storageEnum";

// @ts-ignore
import UserPageApi from "@/api/flow/UserPageApi.js";
import {userPageProject} from "@/store/modules/flow/userPageProject";
// @ts-ignore
import Utils from "@/vue2-flow/src/utils/Common.js";
import {UserComponent} from "@/api/UserComponentsApi";

const PageProject = userPageProject()
const {LayersIcon, BarChartIcon, PrismIcon, HomeIcon, ArrowBackIcon, ArrowForwardIcon, SaveIcon} = icon.ionicons5
const {setItem} = useChartLayoutStore()
const {getLayers, getCharts, getDetails} = toRefs(useChartLayoutStore())
const chartEditStore = useChartEditStore()
const chartHistoryStore = useChartHistoryStore()
const routerParamsInfo = useRoute()

interface ItemType<T> {
  key: T
  select: Ref<boolean> | boolean
  title: string
  icon: any
}

const btnList = reactive<ItemType<ChartLayoutStoreEnum>[]>([
  {
    key: ChartLayoutStoreEnum.CHARTS,
    select: getCharts,
    title: '图表组件',
    icon: renderIcon(BarChartIcon)
  },
  {
    key: ChartLayoutStoreEnum.LAYERS,
    select: getLayers,
    title: '图层控制',
    icon: renderIcon(LayersIcon)
  },
  {
    key: ChartLayoutStoreEnum.DETAILS,
    select: getDetails,
    title: '详情设置',
    icon: renderIcon(PrismIcon)
  }
])

const isBackStack = computed(() => chartHistoryStore.getBackStack.length > 1)

const isForwardStack = computed(() => chartHistoryStore.getForwardStack.length > 0)

const historyList = reactive<ItemType<HistoryStackEnum>[]>([
  {
    key: HistoryStackEnum.BACK_STACK,
    // 一定会有初始化画布
    select: isBackStack,
    title: '后退',
    icon: renderIcon(ArrowBackIcon)
  },
  {
    key: HistoryStackEnum.FORWARD_STACK,
    select: isForwardStack,
    title: '前进',
    icon: renderIcon(ArrowForwardIcon)
  }
])
const saveList = reactive<ItemType<HistoryStackEnum>[]>([
  {
    key: HistoryStackEnum.SAVE_STACK,
    select: true,
    title: '保存',
    icon: renderIcon(SaveIcon)
  }
])

// store 描述的是展示的值，所以和 ContentConfigurations 的 collapsed 是相反的
const styleHandle = (item: ItemType<ChartLayoutStoreEnum>) => {
  if (item.key === ChartLayoutStoreEnum.DETAILS) {
    return item.select ? '' : 'primary'
  }
  return item.select ? 'primary' : ''
}

// 布局处理
const clickHandle = (item: ItemType<ChartLayoutStoreEnum>) => {
  setItem(item.key, !item.select)
}

// 历史记录处理
const clickHistoryHandle = (item: ItemType<HistoryStackEnum>) => {
  switch (item.key) {
    case HistoryStackEnum.BACK_STACK:
      chartEditStore.setBack()
      break;
    case HistoryStackEnum.FORWARD_STACK:
      chartEditStore.setForward()
      break;
  }
}

const clickSaveHandle = (item: ItemType<HistoryStackEnum>) => {
  switch (item.key) {
    case HistoryStackEnum.SAVE_STACK:
      item.select = false
      setTimeout(() => {
        item.select = true
      }, 1500)
      saveUserPageHandle()
      break;
  }
}
// 保存用户界面
const saveUserPageHandle = () => {
  const path = fetchPathByName(PreviewEnum.CHART_PREVIEW_NAME, 'href')
  if (!path) return
  const {id} = routerParamsInfo.params
  // id 标识
  const previewId = typeof id === 'string' ? id : id[0] // gg
  const storageInfo = chartEditStore.getStorageInfo()
  const sessionStorageInfo = getLocalStorage(StorageEnum.GO_CHART_STORAGE_LIST) || []
  if (Utils.IsEmpty(previewId) || Utils.IsEmpty(storageInfo?.componentList) && Utils.IsEmpty(sessionStorageInfo)) {
    MessageError('数据异常，请返回到主页，重新加载！')
    return;
  }
  let Result: { id: string }[] = [];
  if (sessionStorageInfo?.length) {
    const repeateIndex = sessionStorageInfo.findIndex((e: { id: string }) => e.id === previewId)
    // 重复替换
    if (repeateIndex !== -1) {
      sessionStorageInfo.splice(repeateIndex, 1, {id: previewId, ...storageInfo})
      setSessionStorage(StorageEnum.GO_CHART_STORAGE_LIST, sessionStorageInfo)
    } else {
      sessionStorageInfo.push({
        id: previewId,
        ...storageInfo
      })
      setSessionStorage(StorageEnum.GO_CHART_STORAGE_LIST, sessionStorageInfo)
    }
    Result = sessionStorageInfo
  } else {
    Result = [{id: previewId, ...storageInfo}]
    setSessionStorage(StorageEnum.GO_CHART_STORAGE_LIST, Result)
  }
  SaveUserPageComponents(Result)
}
const SaveUserPageComponents = (Result: object) => {
  const CurrentEditPage = 'default'
  const Project = PageProject.GetCurrentEditProject
  UserComponent.Save(Project.Id, CurrentEditPage + '.Component', JSONStringify(Result, 0)).then(res => {
    if (res?.IsSuccess){
      MessageSuccess('保存成功！')
    }else {
      MessageError('保存失败！')
    }
  })
   // upa.SaveUserPageComponents(Project.Id,
   //     CurrentEditPage + '.Component', JSONStringify(Result, 0), () => {
   // })
  // upa.SaveUserPageComponents(CurrentEditPage + '.Style', JSONStringify(v), () => {
  // })
}
// 返回首页
const goHomeHandle = () => {
  goDialog({
    message: '请确定是否已经保存，返回将不会保存任何操作',
    isMaskClosable: true,
    onPositiveCallback: () => {
      goHome()
      useRemoveKeyboard()
    }
  })
}
</script>
<style lang="scss" scoped>
.header-left-btn {
  margin-left: -37px;
}
</style>
